/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fsd.semana3.aula.echoeventoo;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author nfsa
 */
public class Echo {

    private SelectionKey key;
    private List<ByteBuffer> list;

    public Echo (SelectionKey _key)
    {
        list = new ArrayList<ByteBuffer>();
        key = _key;
    }

    public void handleRead() throws IOException
    {
        SocketChannel socket = (SocketChannel) key.channel();
        ByteBuffer buf = ByteBuffer.allocate(256);
        int ammount = socket.read(buf);
        if (ammount <= 0) {
            key.cancel();
            key.channel().close();
        }
        else
        {
            buf.flip();
            list.add(buf);
            if (list.size() > 100) {
                key.interestOps(SelectionKey.OP_WRITE);
            }
            else {
                key.interestOps(SelectionKey.OP_WRITE | SelectionKey.OP_READ);
            }
        }
    }

    public void handleWrite() throws IOException
    {
        SocketChannel socket = (SocketChannel) key.channel();
        ByteBuffer buf = list.remove(0);
        socket.write(buf);
        if (list.isEmpty()) {
            key.interestOps(SelectionKey.OP_READ);
        }
        else {
            key.interestOps(SelectionKey.OP_WRITE | SelectionKey.OP_READ);
        }
    }
}
